import socket
import time

class TCPClient:  
    def __init__(self, ip, port):  
        self.ip = ip  
        self.port = port  
        self.socket = None  
        self.connected = False  
  
    def connect(self):  
        try:  
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
            self.socket.connect((self.ip, self.port))  
            self.connected = True  
            print(f"Connected to {self.ip}:{self.port}")  
        except ConnectionRefusedError:
            self.connected = False 
            print('Socket error, do reconnect...')
            time.sleep(3)
        except Exception as e:  
            print(f"Connection failed: {e}")  
            self.connected = False  
  
    def send_message(self, message_frame):  
        if self.connected:  
            try:  
                self.socket.sendall(message_frame)  
                print("Message sent.")  
            except Exception as e:  
                print(f"Failed to send message: {e}")  
                self.connected = False  
  
    def receive_data(self):  
        if self.connected:  
            try:  
                data = self.socket.recv(1024)  
                if data.decode('utf-8').strip() == "Hello":  
                    print(f"Received {data.decode('utf-8')} from {self.ip}:{self.port}.")  
                    return True  
                else:  
                    print(f"Received unexpected data: {data.decode('utf-8')}")  
            except Exception as e:  
                print(f"Failed to receive data: {e}")  
                self.connected = False  
        return False  
  
    def close_connection(self):  
        if self.socket:  
            self.socket.close()  
            self.connected = False  
